//
//  ImageDownloadOperation.m
//  WoWeibo
//
//  Created by Jaedong n.Die_ on 12-5-31.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ImageDownloadOperation.h"

@implementation ImageDownloadOperation

@synthesize delegate = _delegate;
@synthesize imageURL = _imageURL;

- (id)initWithURL:(NSURL *)requestURL {

    self = [super init];
    if(self) {
    
        _imageURL = [requestURL retain];
    }
    
    return self;
}

- (void)main {


    NSURLResponse *response = nil;
    NSData *data = [NSURLConnection sendSynchronousRequest:[NSURLRequest requestWithURL:_imageURL] returningResponse:&response error:nil];
    if(((NSHTTPURLResponse *)response).statusCode == 200) {
    
        if(_delegate != nil && [_delegate respondsToSelector:@selector(imageDidDownloadSuccessed:withURL:)]) {
            
            NSMethodSignature *signature = [(id)_delegate methodSignatureForSelector:@selector(imageDidDownloadSuccessed:withURL:)];
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
            invocation.target = _delegate;
            invocation.selector = @selector(imageDidDownloadSuccessed:withURL:);
            [invocation setArgument:&data atIndex:2];
            [invocation setArgument:&_imageURL atIndex:3];
            [invocation retainArguments];
            
            [invocation performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:NO];
        }
    }else {
        
        if(_delegate != nil && [_delegate respondsToSelector:@selector(imageDidDownloadFailed:)]) {
            
            NSMethodSignature *signature = [(id)_delegate methodSignatureForSelector:@selector(imageDidDownloadFailed:)];
            NSInvocation *invocation = [NSInvocation invocationWithMethodSignature:signature];
            invocation.target = _delegate;
            invocation.selector = @selector(imageDidDownloadFailed:);
            [invocation setArgument:&_imageURL atIndex:2];
            [invocation retainArguments];
            
            [invocation performSelectorOnMainThread:@selector(invoke) withObject:nil waitUntilDone:NO];
        }
    }
}

- (BOOL)isConcurrent {

    return YES;
}

- (void)cancel {

    _delegate = nil;
    
    [super cancel];
}

- (void)dealloc {

    [_imageURL release];
    
    _imageURL = nil;
    
    [super dealloc];
}

@end
